package com.ddstation.onsitelaw.controller;


import com.ddstation.onsitelaw.model.auditmodel.UserModel;
import com.ddstation.onsitelaw.service.Wx3thPlatformServiceItf;
import com.ddstation.onsitelaw.utils.Constant;
import com.ddstation.onsitelaw.utils.HttpClient;
import com.ddstation.onsitelaw.utils.MessageUtil;
import com.ddstation.security.util.WnUserIdCrypt;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;


/**
 * @author 陆青龙
 */
@Controller
public class WxController {

    private static final Logger logger = LoggerFactory.getLogger(WxController.class);
    @Inject
    private Wx3thPlatformServiceItf wx3thPlatformServiceItf;

    /**
     * get请求回调url
     *
     * @param msgSignature
     * @param timeStamp
     * @param nonce
     * @param echostr
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "callback")
    @ResponseBody
    public void reveiceMsg(@RequestParam(name = "msg_signature") String msgSignature,
                           @RequestParam(name = "timestamp") String timeStamp,
                           @RequestParam(name = "nonce") String nonce,
                           @RequestParam(name = "echostr") String echostr,
                           HttpServletResponse response) throws Exception {
        //企业回调的url-----该url不做任何的业务逻辑，仅仅微信查看是否可以调通.
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Constant.token, Constant.encodingAesKey, Constant.corpId);
        // 随机字符串
        String sEchoStr = wxcpt.verifyURL(msgSignature, timeStamp, nonce, echostr);
        PrintWriter out = response.getWriter();
        try {
            //必须要返回解密之后的明文
            if (StringUtils.isBlank(sEchoStr)) {
                logger.info("URL验证失败");

            } else {
                logger.info("验证成功!");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.write(sEchoStr);
        out.flush();
    }

    /**
     * post请求回调url
     *
     * @param request
     * @param msgSignature
     * @param timeStamp
     * @param nonce
     * @return
     */

    @PostMapping(value = "callback")
    @ResponseBody
    public String callback(HttpServletRequest request,
                           @RequestParam(name = "msg_signature") String msgSignature,
                           @RequestParam(name = "timestamp") String timeStamp,
                           @RequestParam(name = "nonce") String nonce) {

        String receiveid = request.getParameter("corpid");
        // 指令回调解密参数用suiteID
        if (StringUtils.isEmpty(receiveid)) {
            receiveid = Constant.suiteId;
        }
        try {
            InputStream inputStream = request.getInputStream();
            String postData = IOUtils.toString(inputStream, "UTF-8");
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(Constant.token, Constant.encodingAesKey, receiveid);

            //解密
            String sMsg = wxcpt.decryptMsg(msgSignature, timeStamp, nonce, postData);
            //将post数据转换为map
            Map<String, String> dataMap = MessageUtil.parseXml(sMsg);
            if (!ObjectUtils.isEmpty(dataMap.get("SuiteTicket"))) {
                wx3thPlatformServiceItf.refreshEnterpriseWeChatComponentVerifyTicket(dataMap.get("SuiteTicket"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 获取用回信息回调接口
     *
     * @param code
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "getWxUserInfo", method = RequestMethod.GET)
    public String getWxUserInfo(String code, HttpSession session) throws Exception {

        UserModel userinfo3rd = getUserModel(code);
        if (userinfo3rd == null) {
            throw new RuntimeException("企业微信获取用户信息失败");
        }
        int uid = wx3thPlatformServiceItf.selectWxUser(userinfo3rd);
        if (uid == -1) {
            userinfo3rd.setTypeSource(1);
            uid = wx3thPlatformServiceItf.insertWxUserUUID(userinfo3rd);
        }
        String encryptUid = WnUserIdCrypt.encrypt(uid, 0);
        session.setAttribute("encryptUid", encryptUid);
        return "redirect:login";
    }

    /**
     * 请求企业微信获取访问用户身份
     *
     * @param code
     * @return
     * @throws IOException
     */
    public UserModel getUserModel(String code) throws IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserinfo3rd?";
        url = url + "suite_access_token=" + wx3thPlatformServiceItf.getEnterpriseWeChatSuiteAccessToken()
                + "&code=" + code;
        String msg = HttpClient.doGet(url);
        //转换首字母大写的key
        msg = msg.replace("UserId", "userId");
        msg = msg.replace("CorpId", "corpId");
        msg = msg.replace("DeviceId", "deviceId");
        JSONObject fromObject = JSONObject.fromObject(msg);
        if (fromObject.get("errcode") == null || "0".equals(fromObject.get("errcode").toString())) {
            UserModel bean = (UserModel) JSONObject.toBean(fromObject, UserModel.class);
            if (bean.getUser_ticket() != null) {
                UserModel userdetail3rd = getUserdetail3rd(bean.getUser_ticket());
                if (userdetail3rd != null) {
                    bean.setAvatar(userdetail3rd.getAvatar());
                    bean.setQr_code(userdetail3rd.getQr_code());
                    bean.setGender(userdetail3rd.getGender());
                    bean.setName(userdetail3rd.getName());
                    bean.setDepartment(userdetail3rd.getDepartment());
                }
            }
            return bean;
        } else {
            logger.error(msg);
        }
        return null;
    }

    /**
     * 获取访问用户敏感信息
     *
     * @param user_ticket
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public UserModel getUserdetail3rd(String user_ticket) throws ClientProtocolException, IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/getuserdetail3rd?";
        url = url + "suite_access_token=" + wx3thPlatformServiceItf.getEnterpriseWeChatSuiteAccessToken();
        JSONObject paramJson = new JSONObject();
        paramJson.put("user_ticket", user_ticket);
        String msg = HttpClient.sendPost(url, paramJson, "utf-8");
        JSONObject fromObject = JSONObject.fromObject(msg);
        if (fromObject.get("errcode") == null || "0".equals(fromObject.get("errcode").toString())) {
            UserModel bean = (UserModel) JSONObject.toBean(fromObject, UserModel.class);
            return bean;
        } else {
            logger.debug(msg);
        }
        return null;
    }


    public static String getWebAgentUri(String redirectUri, String scope) throws UnsupportedEncodingException {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?";
        return url = url + "appid=" + Constant.suiteId
                + "&redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8")
                + "&response_type=code"
                + "&scope=" + scope
                + "#wechat_redirect";
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String webAgentUri = getWebAgentUri("http://7b2sxf.natappfree.cc/onsitelaw/getWxUserInfo", "snsapi_privateinfo");
    }


}